package com.luck.picture.lib.util;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.Log;

import com.luck.picture.lib.listener.AddBitmapWatermarkListener;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class PictureBitmapCompress {
	public static void compressImageScaleStream(String srcPath, long fileSize, float hh, float ww,
												AddBitmapWatermarkListener addBitmapWatermarkListener, String labelLocation,
												int paddingLeftRight, int paddingTopBottom) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap;//此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		//float hh = 800f;//这里设置高度为800f
		//float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = Math.round (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be =  Math.round (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		//be = (int) ((w / STANDARD_WIDTH + h/ STANDARD_HEIGHT) / 2);
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

		compressImageBySizeStream(bitmap, addBitmapWatermarkListener,srcPath,fileSize,labelLocation,paddingLeftRight,paddingTopBottom);//压缩好比例大小后再进行质量压缩

	}

	public static void compressImageBySizeStream(Bitmap image, AddBitmapWatermarkListener onWaterMarkCreateListene,
												 String srcPath, long fileSize, String labelLocation,
												 int paddingLeftRight, int paddingTopBottom) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int options = 100;

		image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中

		//这里把图片旋转
		int degree = BitmapRotating.readPictureDegree(srcPath);
		Bitmap bitmapRoota = BitmapRotating.rotaingImageView(degree, image);

		Bitmap waterMark= null;
		if (onWaterMarkCreateListene!=null){
			waterMark=onWaterMarkCreateListene.addBitmapWatermark(bitmapRoota.getWidth(),bitmapRoota.getHeight());
		}

		Bitmap newbitmap = ImageUtils.createWaterMask(bitmapRoota,waterMark,labelLocation,paddingLeftRight,paddingTopBottom);


		ByteArrayInputStream isBm = getByteArrayInputStream(fileSize,baos,options,newbitmap);// 把压缩后的数据baos存放到ByteArrayInputStream中

		FileOutputStream fos;
		try {
			fos = new FileOutputStream(srcPath);
			byte[] buf = new byte[1024];
			int len;
			try {
				if (isBm != null) {
					while ((len = isBm.read(buf)) > 0) {
						fos.write(buf, 0, len);
					}
					isBm.close();
					fos.flush();
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.i("tag",fos.toString());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



//
//		FileService fileService = AppContext.getInstance().getFileServer();
//		if (fileService.getCamreaMessage() != null
//				&& !("").equals(fileService.getCamreaMessage())
//		) {
//			String[] camreaMessage = fileService.getCamreaMessage().split(",");
//			String text = "";
//			for (int i = 0; i < camreaMessage.length; i++) {
//				if (i + 1 == camreaMessage.length) {
//					if (camreaMessage[i].equals("dateTime")) {
//						text += MyDateTools.getDate("date_time");
//					} else if (camreaMessage[i].equals("addr")) {
//						text += AppContext.getInstance().getCurLocation().getAddr();
//					} else if (camreaMessage[i].equals("userName")) {
//						text += "上报人：" + AppContext.getInstance().getCurUser().getUserAlias();
//					}
//				} else {
//					if (camreaMessage[i].equals("dataTime")) {
//						text += MyDateTools.getDate("date_time") + ",";
//					} else if (camreaMessage[i].equals("addr")) {
//						text += AppContext.getInstance().getCurLocation().getAddr() + ",";
//					} else if (camreaMessage[i].equals("userName")) {
//						text += "上报人：" + AppContext.getInstance().getCurUser().getUserAlias() + ",";
//					}
//				}
//			}
//			Bitmap newBitmap = Bitmap.createBitmap(bitmapRoota.getWidth(), bitmapRoota.getHeight(), Config.ARGB_4444);
//			Bitmap newbitmap = createBitmap(bitmapRoota, null, text, newBitmap, fileService.getLabelLocation());
//			return getByteArrayInputStream(fileSize, baos, options, newbitmap);
//		} else {
//			return getByteArrayInputStream(fileSize, baos, options, bitmapRoota);
//		}
	}

	/**
	 * 进行添加水印图片和文字
	 *
	 * @param src
	 * @param waterMak
	 * @param labelLocation
	 * @return
	 */
	public static  Bitmap createBitmap(Bitmap src, Bitmap waterMak, String title,Bitmap newBitmap, String labelLocation) {
		if (src == null) {
			return src;
		}
		// 获取原始图片与水印图片的宽与高
		int w = src.getWidth();
		int h = src.getHeight();

		Canvas mCanvas = new Canvas(newBitmap);
		// 往位图中开始画入src原始图片
		mCanvas.drawBitmap(src, 0, 0, null);
		// 在src的右下角添加水印
		Paint paint = new Paint();
		//paint.setAlpha(100);
		if(waterMak!=null){
			int ww = waterMak.getWidth();
			int wh = waterMak.getHeight();
			mCanvas.drawBitmap(waterMak, w - ww - 5, h - wh - 5, paint);
		}

		if(labelLocation.equals("")||labelLocation==null){
			labelLocation = "leftDown";
		}

		// 开始加入文字
		if (null != title) {
			String[] text = title.split(",");
			for (int i = 1; i <= text.length; i++) {

				String str=text[i-1];

				Paint textPaint = new Paint();
				textPaint.setColor(Color.YELLOW);
				textPaint.setTextSize(24);
				String familyName = "宋体";
				Typeface typeface = Typeface.create(familyName,
						Typeface.BOLD_ITALIC);
				textPaint.setTypeface(typeface);
				//           textPaint.setTextAlign(Align.CENTER);

				if(labelLocation.equals("rightDown")){
					int x=w-250;
					int y=h-(25+30*(text.length-i));
					mCanvas.drawText(str, x, y, textPaint);
				}else if(labelLocation.equals("leftDown")){
					int x=25;
					int y=h-(25+30*(text.length-i));
					mCanvas.drawText(str, x, y, textPaint);
				}else if(labelLocation.equals("rightUp")){
					int x=w-250;
					int y=40+30*i;
					mCanvas.drawText(str, x, y, textPaint);
				}else if(labelLocation.equals("leftUp")){
					int x=25;
					int y=40+30*i;
					mCanvas.drawText(str, x, y, textPaint);
				}
			}
		}
		mCanvas.save();
		mCanvas.restore();
		if(waterMak!=null){
			waterMak.recycle();
		}
		src.recycle();
		return newBitmap;
	}

	private static ByteArrayInputStream getByteArrayInputStream(long fileSize, ByteArrayOutputStream baos, int options, Bitmap bitmapRoota) {
		byte tmp[] = baos.toByteArray();
		if (tmp.length / 1024 > fileSize){
			while (tmp.length / 1024 > fileSize) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
				options -= 10;// 每次都减少10
				if (options > 0) {
					baos.reset();// 重置baos即清空baos
					bitmapRoota.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
					tmp = baos.toByteArray();

					if (baos != null) {
						try {
							baos.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				} else {
					break;
				}
			}
		}else {
			baos.reset();// 重置baos即清空baos
			bitmapRoota.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			tmp = baos.toByteArray();

			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		//Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return isBm;
	}


}
